package com.example.hyg_veintype.activity.account.login;

import android.content.Context;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ToggleButton;

import com.example.hyg_veintype.R;
import com.example.hyg_veintype.activity.MainActivity;
import com.example.hyg_veintype.activity.account.register.RegisterActivity;
import com.example.hyg_veintype.base.BaseHandler;
import com.example.hyg_veintype.base.api.ApiServiceManager;
import com.example.hyg_veintype.base.api.IGsonResponse;
import com.example.hyg_veintype.base.baseadapter.BaseHolder;
import com.example.hyg_veintype.base.baseadapter.BaseRecyclerAdapter;
import com.example.hyg_veintype.constant.account.AccountConst;
import com.example.hyg_veintype.data.net.loginPassword.LoginPasswordWraper;
import com.example.hyg_veintype.data.net.smscodeGet.SmsCodeGetWraper;
import com.example.hyg_veintype.view.CustomProgressDialog;
import com.hyg.lib_base.mainUtils.ToastUtils;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.sweetalertdialog.SweetAlertDialog;


import java.util.List;


import okhttp3.FormBody;

import static com.hyg.lib_common.constant.UrlUtils.codeaddr;
import static com.hyg.lib_common.constant.UrlUtils.loginPhoneAddr;
import static com.hyg.lib_common.constant.UrlUtils.loginPwdAddr;

/**
 * @author: yyw
 * time: 2020/12/21 16:51
 * desc:
 */
public class LoginVpAdapter extends BaseRecyclerAdapter<Integer> implements BaseHandler.OnReceiveMessageListener {

    EditText userphone;
    EditText password;
    ToggleButton togglePwd;
    EditText userphone2;
    EditText etCode;
    Button getcode;

    private static final int loginType1 = 1;//密码登录
    private static final int loginType2 = 2;//快捷登录

    public String mphone = "[1][345789]\\d{9}";//第一位是数字1，第二位是358中的一个在加上9个数字
    public String mcode = "\\d{4,6}";//第一位是数字1，第二位是358中的一个在加上9个数字
    public String mpassword = "[A-Za-z0-9]{6,18}";//第一位是字母，后面加上4-15个
    private static final int MSG_SENDPIN = 1001;
    private static final int COUNT_SECOND = 60;
    private static int msgIndex = 60;

    public SweetAlertDialog pDialog;
    CustomProgressDialog progressDialog;
    BaseHandler baseHandler;

    public LoginVpAdapter(List<Integer> infos, Context context, CustomProgressDialog progressDialog) {
        super(infos, context);
        this.progressDialog = progressDialog;
        baseHandler = new BaseHandler(this);
        pDialog = new SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE);
        pDialog.setConfirmButton("好，知道啦", new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
            }
        });

    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return loginType1;
        } else {
            return loginType2;
        }
    }

    @Override
    public BaseHolder<Integer> getHolder(View v, int viewType) {
        if (viewType == loginType1) {
            return new MyHolder1(v, context);
        } else {
            return new MyHolder2(v, context);
        }
    }

    @Override
    public int getLayoutId(int viewType) {
        if (viewType == loginType1) {
            return R.layout.veintype_login_pass;
        } else {
            return R.layout.veintype_login_phone;
        }
    }


    /************** 密码登录 **************/
    class MyHolder1 extends BaseHolder {
        Button forget;
        Button login;
        Button bt_register;
        public MyHolder1(View itemView, Context context) {
            super(itemView, context);
            userphone = itemView.findViewById(R.id.userphone);
            password = itemView.findViewById(R.id.password);
            togglePwd = itemView.findViewById(R.id.togglePwd);
            togglePwd.setOnClickListener(this);
            forget=itemView.findViewById(R.id.forget);
            forget.setOnClickListener(this);
            login=itemView.findViewById(R.id.login);
            login.setOnClickListener(this);
            bt_register=itemView.findViewById(R.id.bt_register);
            bt_register.setOnClickListener(this);
        }

        @Override
        public void setData(Object data, int position) {
        }

        @Override
        public void onClick(View view) {
            if (Utils.isFastClick()) {
                return;
            }
            int id = view.getId();
            if (id == R.id.togglePwd) {
                if (togglePwd.isChecked()) {//显示密码
                    password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {//隐藏密码
                    password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            } else if (id == R.id.forget) {
                RegisterActivity.start(context, RegisterActivity.INDEX_FORGET);
            } else if (id == R.id.login) {
                doLogin(loginType1, userphone.getText().toString(), password.getText().toString());
            } else if (id == R.id.bt_register) {
                RegisterActivity.start(context, RegisterActivity.INDEX_REGISTER);
            }
        }
    }

    /************** 验证码登录 **************/
    @Override
    public void handlerMessage(Message msg) {
        switch (msg.what) {
            case MSG_SENDPIN:
                if (msgIndex > 0) {
                    msgIndex--;
                    getcode.setText(msgIndex + "s后可获取");
                    getcode.setEnabled(false);
                    getcode.setAlpha(0.5f);
                    baseHandler.sendEmptyMessageDelayed(MSG_SENDPIN, 1000);
                } else {//60秒后可再发送
                    msgIndex = COUNT_SECOND;
                    getcode.setEnabled(true);
                    getcode.setText("获取验证码");
                    getcode.setAlpha(0.9f);
                }
                break;
            default:
                break;
        }
    }

    class MyHolder2 extends BaseHolder{
        Button login;
        Button register;
        public MyHolder2(View itemView, Context context) {
            super(itemView, context);
            userphone2 = itemView.findViewById(R.id.userphone);
            etCode = itemView.findViewById(R.id.et_code);
            getcode = itemView.findViewById(R.id.getcode);
            getcode.setOnClickListener(this);
            login=itemView.findViewById(R.id.login);
            login.setOnClickListener(this);
            register=itemView.findViewById(R.id.bt_register);
            register.setOnClickListener(this);

        }

        @Override
        public void setData(Object data, int position) {

        }

        @Override
        public void onClick(View view) {
            int id = view.getId();
            if (id == R.id.getcode) {
                sendCode(userphone2.getText().toString());
            } else if (id == R.id.login) {
                doLogin(2, userphone2.getText().toString(), etCode.getText().toString());
            } else if (id == R.id.bt_register) {
                RegisterActivity.start(context, RegisterActivity.INDEX_REGISTER);
            }
        }
    }

    /**
     * 获取短信验证码
     *
     * @param phone
     */
    private void sendCode(String phone) {
        if (pDialog.isShowing()) {
            pDialog.dismiss();
        }
        pDialog = new SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE);
        pDialog.setTitleText("格式错误");
        if (TextUtils.isEmpty(phone)) {
            pDialog.setContentText("电话号码不可为空，请填写电话号码").show();
            return;
        }
        if (!phone.matches(mphone)) {
            pDialog.setContentText("电话号码格式不对，请重新输入。").show();
            return;
        }
        etCode.setHint("请注意查看短信");
        FormBody formBody = new FormBody.Builder()
                .add("phone", phone)//设置参数名称和参数值
                .build();
        progressDialog.show();
        ApiServiceManager.getInstance().postRequest(codeaddr, formBody, SmsCodeGetWraper.class, new IGsonResponse<SmsCodeGetWraper>() {

            @Override
            public void onSuccess(SmsCodeGetWraper model, String response) {
                progressDialog.dismiss();
                if (model.getCode() == 200) {
                    getcode.setEnabled(false);
                    baseHandler.sendEmptyMessageDelayed(MSG_SENDPIN, 1000);
                    if (!TextUtils.isEmpty(model.getMessage())) {
                        ToastUtils.showShort(model.getMessage());
                    }
                } else {
                    pDialog.setTitleText("获取短信失败");
                    if (TextUtils.isEmpty(model.getMessage())) {
                        pDialog.setContentText("未知异常").show();
                    } else {
                        pDialog.setContentText(model.getMessage()).show();
                    }
                }
            }

            @Override
            public void onError(String msg) {
                progressDialog.dismiss();
                pDialog.setTitleText("获取短信失败");
                pDialog.setContentText("网络错误").show();
            }
        });
    }

    /**
     * 登录方法
     *
     * @param index    loginType1（1密码登录）loginType2（2验证码登录）
     * @param username 手机号
     * @param password 密码/验证码
     */
    private void doLogin(int index, String username, String password) {
        if (pDialog.isShowing()) {
            pDialog.dismiss();
        }
        pDialog = new SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE);
        pDialog.setTitleText("格式错误");
        if (TextUtils.isEmpty(username)) {
            pDialog.setContentText("请填写手机号").show();
            return;
        }
        if (!username.matches(mphone)) {
            pDialog.setContentText("手机号格式错误，请重新输入").show();
            return;
        }
        if (index == loginType1) {
            //密码登录
            if (TextUtils.isEmpty(password)) {
                pDialog.setContentText("密码不可为空，请填写密码。").show();
                return;
            }
            if (!password.matches(mpassword)) {
                pDialog.setContentText("密码格式不对或者包含非格式字符，请重新输入").show();
                return;
            }
            FormBody formBody = new FormBody.Builder()
                    .add("phone", username)
                    .add("password", password)
                    .build();
            progressDialog.show();
            ApiServiceManager.getInstance().postRequest(loginPwdAddr, formBody, LoginPasswordWraper.class, new IGsonResponse<LoginPasswordWraper>() {
                @Override
                public void onSuccess(LoginPasswordWraper model, String response) {
                    progressDialog.dismiss();
                    if (model.getCode() == 200) {
                        AccountConst.saveAccountData(context,
                                username,
                                password,
                                model.getData().getData().getToken());
                        MainActivity.start(context);
                    } else {
                        pDialog.setTitleText("登录失败")
                                .setContentText(model.getData().getMessage())
                                .show();
                    }
                }

                @Override
                public void onError(String msg) {
                    progressDialog.dismiss();
                    pDialog.setTitleText("登录失败")
                            .setContentText("网络异常")
                            .show();
                }
            });

        } else if (index == loginType2) {
            //验证码登录
            if (TextUtils.isEmpty(password)) {
                pDialog.setContentText("请填写验证码").show();
                return;
            }
            if (!password.matches(mcode)) {
                pDialog.setContentText("验证码格式错误，请重新输入").show();
                return;
            }
            FormBody formBody = new FormBody.Builder()
                    .add("phone", username)
                    .add("smsCode", password)
                    .build();
            progressDialog.show();
            ApiServiceManager.getInstance().postRequest(loginPhoneAddr, formBody, LoginPasswordWraper.class, new IGsonResponse<LoginPasswordWraper>() {
                @Override
                public void onSuccess(LoginPasswordWraper model, String response) {
                    progressDialog.dismiss();
                    if (model.getCode() == 200) {
                        AccountConst.saveAccountData(context,
                                username,
                                password,
                                model.getData().getData().getToken());
                        MainActivity.start(context);
                    } else {
                        pDialog.setTitleText("登录失败");
                        pDialog.setContentText(model.getMessage()).show();
                    }
                }

                @Override
                public void onError(String msg) {
                    progressDialog.dismiss();
                    pDialog.setTitleText("登录失败");
                    pDialog.setContentText("网络异常").show();
                }
            });

        }

    }
}
